package cn.org.eshow.dao.hibernate;

import cn.org.eshow.bean.query.MoneyQuery;
import cn.org.eshow.common.dao.EnhancedRule;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.dao.MoneyDao;
import cn.org.eshow.model.Money;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository("moneyDao")
public class MoneyDaoHibernate extends GenericDaoHibernate<Money, Integer> implements MoneyDao {

    public MoneyDaoHibernate() {
        super(Money.class);
    }

    @Override
    public List<Money> list(MoneyQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        return list(rule);
    }

    @Override
    public Page<Money> search(MoneyQuery query) {
        EnhancedRule rule = new EnhancedRule();
        setRule(rule, query);
        if (query != null) {
            rule.setOffset(query.getOffset());
            rule.setPageSize(query.pagesize);
        }
        return page(rule);
    }


    public EnhancedRule setRule(EnhancedRule rule, MoneyQuery query) {
        if (query != null) {
            if (query.startAddTime != null) {
                rule.add(Restrictions.ge("addTime", query.startAddTime));
            }
            if (query.endAddTime != null) {
                rule.add(Restrictions.le("addTime", query.endAddTime));
            }
            if (query.startUpdateTime != null) {
                rule.add(Restrictions.ge("updateTime", query.startUpdateTime));
            }
            if (query.endUpdateTime != null) {
                rule.add(Restrictions.le("updateTime", query.endUpdateTime));
            }
            if (query.minBalance != null) {
                rule.add(Restrictions.ge("balance", query.minBalance));
            }
            if (query.maxBalance != null) {
                rule.add(Restrictions.le("balance", query.maxBalance));
            }
            if (query.enabled != null) {
                rule.add(Restrictions.eq("enabled", query.enabled));
            }
            if (query.userId != null) {
                rule.add(Restrictions.eq("user.id", query.userId));
            }
            if (!StringUtils.isEmpty(query.getOrder())) {
                rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder()));
            }
        }
        return rule;
    }
}
